# -*- coding: utf-8  -*-
#!/usr/local/bin/python

__author__ = 'jian.yao'

from django.core.cache import cache as django_cache
from django.core.cache import get_cache
from django.utils.encoding import smart_str
from hashlib import md5 as md5_constructor

class Cache:
    def __init__(self, backend=None):
        if backend:
            _cache_cls = get_cache(backend)
        else:
            _cache_cls = django_cache

        self.cache_backend = _cache_cls

    def set(self, key, value, timeout = None):
        if isinstance(value, unicode):
            value = value.encode("utf-8")
        if timeout is None:
            timeout = self.cache_backend.default_timeout
        self.cache_backend.set(self.__smart_key__(key), value, timeout)

    def get(self, key):
        return self.cache_backend.get(self.__smart_key__(key))

    def __smart_key__(self, key):
        if len(key) > 250:
            return md5_constructor(smart_str(key)).hexdigest()
        else:
            return smart_str(key)
